/**
 * @class ClientManager
 * @description 记录连接的客户端对应的rtsp
 */
class ClientManager {
  constructor() {
    // id: rtsp 映射表
    this.clientMap = new Map();
  }

  /**
   * 根据用户id添加一个或者多个rtsp地址
   *
   * @param {string} id uuid
   * @param {string|string[]} rtsp 流地址
   */
  add(id, rtsp) {
    console.log("🚀 ~ add ~ rtsp:", rtsp);
    if (typeof rtsp === "string") {
      this.addOneRtsp(id, rtsp);
    } else if (Array.isArray(rtsp)) {
      this.addManyRtsp(id, rtsp);
    }
  }

  /**
   * 根据用户id添加一个rtsp地址
   *
   * @param {string} id uuid
   * @param {string} rtsp 流地址
   */
  addOneRtsp(id, rtsp) {
    console.log("🚀 ~ addOneRtsp ~ rtsp:", rtsp);
    if (!this.clientMap.has(id)) {
      this.clientMap.set(id, new Set());
    }
    this.clientMap.get(id).add(rtsp);
  }

  /**
   * 添加多个rtsp地址
   *
   * @param {string} id uuid
   * @param {string[]} rtsps 流地址数组
   */
  addManyRtsp(id, rtsps) {
    console.log("🚀 addManyRtsp ~ rtsps:", rtsps);
    rtsps.forEach((rtsp) => {
      this.addOneRtsp(id, rtsp);
    });
  }

  /**
   * 删除用户，返回该用户的rtsp
   * @param {string} id uuid
   * @returns {string[]} - 该用户所有的流地址
   */
  removeById(id) {
    const rtsps = Array.from(this.clientMap.get(id) || []);
    this.clientMap.delete(id);
    return rtsps;
  }

  /**
   * 根据clientId删除rtsp
   * @param {string} [id]
   * @param {string|string[]} rtsp
   */
  removeRtsp(id, rtsp) {
    // 如果没有id，遍历所有client，删除启动的rtsp
    console.log("如果没有id，遍历所有client，删除启动的rtsp", id);
    if (!id) return this.removeRtspAllClents(rtsp);

    if (typeof rtsp === "string") return this.removeOneRtsp(id, rtsp);
    if (Array.isArray(rtsp)) return this.removeManyRtsps(id, rtsp);
  }

  /**
   * @param {string} rtsp
   */
  removeRtspAllClents(rtsp) {
    console.log("removeRtspAllClents", rtsp);
    this.clientMap.values((rtspSet) => rtspSet.delete(rtsp));
  }

  /**
   *
   * @param {string} id
   * @param {string} rtsp
   */
  removeOneRtsp(id, rtsp) {
    if (!this.clientMap.has(id)) return;
    this.clientMap.get(id).delete(rtsp);
  }

  /**
   *
   * @param {string} id
   * @param {string[]} rtsps
   */
  removeManyRtsps(id, rtsps) {
    rtsps.forEach((rtsp) => this.removeOneRtsp(id, rtsp));
  }

  /**
   * 获取去重后所有的rtsp
   * @returns {string[]} - 所有的rtsp流地址
   */
  getAllRtsp() {
    return Array.from(
      new Set([...this.clientMap.values()].map((set) => Array.from(set)).flat())
    );
  }
}
module.exports = {
  ClientManager,
};
